﻿#region Copyrights Notice
//©2010 Microsoft Corporation. All rights reserved.
#endregion

#region usings
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.DirectoryServices.AccountManagement;
using System.Security.Principal;
using System.Xml;
using System.IO;
using System.Web.Hosting;
#endregion

namespace Microsoft.InformationSecurity.CISF.Common.Utilities
{
    public static class Utility
    {
        static string[] aryAuthUser = new string[2];

        /// <summary>
        /// Returns logged in username in the domain\user format.
        /// </summary>
        /// <returns>Username</returns>
        public static string GetUserFullName(string strUserName)
        {
            string strUserAlias=String.Empty;
            string strDomain = String.Empty;

            //getting user name/domain from identity
            strUserAlias = GetUserAlias(strUserName);
            strDomain = GetUserDomain(strUserName);

            //creating user principal object and filling the principal returned by the Utility class
            UserPrincipal userPrinObj = GetUserPrincipal(strUserAlias,strDomain);

            //checking its not null
            if (userPrinObj != null)
            {
                return userPrinObj.DisplayName;
            }
            else
            {
                //else return user alias
                return strUserAlias;
            }
        }

        /// <summary>
        /// Returns logged in username in the domain\user format.
        /// </summary>
        /// <returns>Username</returns>
        public static string GetUsername()
        {
            try
            {
                //getting user identity from HTTP context
                return System.Web.HttpContext.Current.User.Identity.Name.ToLower();
            }
            catch
            {
                return "Error: User Identity not found!";
            }
        }

        /// <summary>
        /// Returns logged in username *** TO SUPPORT BACKWARD COMPATIBILITY ***
        /// </summary>
        /// <param name="includeDomain">Includes domain portion of the username</param>
        /// <returns>Username</returns>
        public static string GetUsername(bool includeDomain)
        {
            if (includeDomain == true)
                return HttpContext.Current.User.Identity.Name;
            else
                return HttpContext.Current.User.Identity.Name.Substring(HttpContext.Current.User.Identity.Name.IndexOf("\\") + 1);
        }

        /// <summary>
        /// Returns logged in username
        /// </summary>
        /// <param name="userName">user name with domain portion</param>
        /// <returns>User Alias</returns>
        public static string GetUserAlias(string strUserName)
        {
            if (string.IsNullOrEmpty(strUserName))
                return "Error: strUserName is null or empty";
            return strUserName.Substring(strUserName.IndexOf("\\") + 1);
        }

        /// <summary>
        /// Returns logged in user domain
        /// </summary>
        /// <returns>Domainname</returns>
        public static string GetUserDomain(string strUserName)
        {
            if (string.IsNullOrEmpty(strUserName))
                return "Error: strUserName is null or empty";
            return strUserName.Substring(0, strUserName.IndexOf("\\"));
        }


        /// <summary>
        /// Returns the user principal object per input user details
        /// </summary>
        /// <param name="userAlias">user alias</param>
        /// <param name="domainName">user domain name</param>
        /// <returns>User Principal Object</returns>
        public static UserPrincipal GetUserPrincipal(string userAlias, string domainName)
        {
            //Code to validate userAlias. If userAlias is invalid, throw ArgumentException with Alias either blank or invalid
            //TODO

            //Code to validate domainName. If domainName is invalid, throw ArgumentException with Domain Name either blank or invalid
            //TODO

            PrincipalContext principalContext = null;
            UserPrincipal userPrincipal = null;
            try
            {
                using (HostingEnvironment.Impersonate())
                {
                    principalContext = new PrincipalContext(ContextType.Domain, domainName);
                    //find the user principal
                    userPrincipal = UserPrincipal.FindByIdentity(principalContext, userAlias);
                    if (userPrincipal == null)
                        throw new ArgumentException("Not able to resolve user alias in given domain.");
                }
            }
            catch (Exception)
            {
                //Here u can get PrincipalServerDownException, COMException in case there is problem connecting to domain
                //throw;
                return null;
            }
            return userPrincipal;
        }
    }
}
